package com.cyt.work.question.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.excel.export.ExcelExportService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.*;
import com.cyt.sys.model.po.SysUser;
import com.cyt.sys.service.impl.BaseServiceImpl;
import com.cyt.sys.util.EasyPoiUtil;
import com.cyt.sys.util.ExcelExportStylerUtil;
import com.cyt.sys.util.FilePathUtil;
import com.cyt.work.question.dao.QuestionDao;
import com.cyt.work.question.model.dto.QuestionDto;
import com.cyt.work.question.model.dto.QuestionUserDto;
import com.cyt.work.question.model.po.*;
import com.cyt.work.question.model.vo.*;
import com.cyt.work.question.service.*;
import com.cyt.work.site.model.po.Notice;
import com.cyt.wx.model.po.WxEducationUser;
import com.cyt.wx.model.vo.WxEducationUserVo;
import com.cyt.wx.service.WxEducationUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.iherus.codegen.qrcode.SimpleQrcodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * 问卷管理表 service实现
 *
 * @author concong tao
 * @since 2019-01-31
 */
@Service
public class QuestionServiceImpl extends BaseServiceImpl<Question> implements IQuestionService {

    @Autowired
    private IQuestionSubjectService questionSubjectService;
    @Autowired
    private IQuestionSubjectSelectService questionSubjectSelectService;
    @Autowired
    private IQuestionScoreService questionScoreService;
    @Autowired
    private IQuestionUserService questionUserService;
    @Autowired
    private WxEducationUserService wxEducationUserService;

    @Autowired
    private QuestionDao questionDao;
    @Autowired
    public void setBaseDao(QuestionDao questionDao) {
        this.baseDao = questionDao;
    }

    @Override
    public ReturnResult page(QuestionVo questionVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" create_time desc");
        Example example = new Example(Question.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(questionVo.getStatus())) {
            criteria.andEqualTo("status", questionVo.getStatus());
        }
        if (StringUtils.isNotEmpty(questionVo.getTitle())) {
            criteria.andLike("title", "%" + questionVo.getTitle() + "%");
        }
        if (StringUtils.isNotEmpty(questionVo.getPageStatus()) && StringUtils.equals(questionVo.getPageStatus(), "2")) {
            criteria.andNotEqualTo("status", "1");
        }
        if (StringUtils.isNotEmpty(questionVo.getApplyId())) {
            criteria.andEqualTo("applyId", questionVo.getApplyId());
        }
        List<Question> list = questionDao.selectByExample(example);
        PageInfo<Question> page = new PageInfo<>(list);
        Map<String, Object> map = new HashedMap();
        map.put("page", page.getList());
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    @Override
    public ReturnResult pageManage(QuestionVo questionVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<QuestionDto> list = questionDao.selectManageList(questionVo);
        PageInfo<QuestionDto> page = new PageInfo<>(list);
        Map<String, Object> map = new HashedMap();
        map.put("page", page.getList());
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    @Override
    public ReturnResult pageLeft(QuestionVo questionVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<QuestionDto> list = questionDao.selectEntityList(questionVo);
        PageInfo<QuestionDto> page = new PageInfo<>(list);
        Map<String, Object> map = new HashedMap();
        map.put("page", page.getList());
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    @Override
    public Question selectFirstQuestion(String applyId) {
        PageHelper.startPage(1, 1);
        PageHelper.orderBy(" create_time desc");
        Example example = new Example(Question.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(applyId)) {
            criteria.andEqualTo("applyId", applyId);
        }
        criteria.andNotEqualTo("status", "1");
        List<Question> list = questionDao.selectByExample(example);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult saveQuestion(HttpServletRequest request, Question question, SysUser sysUser) {
        // 获取id
        String questionId = BaseUtil.uId();
        question.setId(questionId);
        question.setCreateTime(new Date());
        // 需要二维码
        if (StringUtils.equals(question.getType(), BaseConstant.QUESTION_TYPE_QRCODE)) {
            // 生成二维码
            String qrCode = getQrCode(request, questionId, question.getApplyId());
            question.setQrCode(qrCode);
            // 如果是非二维码问卷，则直接删除相关数据
            // 删除以前的数据
            QuestionUser questionUserSearch = new QuestionUser();
            questionUserSearch.setQuestionId(questionId);
            questionUserService.delete(questionUserSearch);
        } else {
            // 如果是自定义对象
            if (StringUtils.equals(question.getObjectType(), BaseConstant.QUESTION_OBJECT_TYPE_CUSTOMIZE)) {
                // 保存进QuestionUser
                questionUserService.saveQuestionUser(questionId, question.getUserJson());
            } else if (StringUtils.equals(question.getObjectType(), BaseConstant.QUESTION_OBJECT_TYPE_ALL)) {
                // 所有人（管理员暂算在内）
                questionUserService.saveQuestionAllWxEducationUser(question.getApplyId(), questionId, sysUser);
            } else {
                // 学生或教师
                questionUserService.saveQuestionWxEducationUserByStatus(question.getApplyId(), questionId, question.getObjectType(), sysUser);
            }
        }
        // 是否是发布中,如果是发布，则需要校验时间，时间未到的，处于未开始状态
        if (StringUtils.equals(question.getStatus(), BaseConstant.QUESTION_STATUS_PUBLISH)) {
            Date startTime = question.getStartTime();
            DateTime nowDate = DateUtil.date();
            String nowStr = DateUtil.formatDate(nowDate);
            if (startTime.getTime() > DateUtil.parseDate(nowStr).getTime()) {
                // 未开始
                question.setStatus(BaseConstant.QUESTION_STATUS_NOT_READY);
            }
        }
        question.setCreateTime(DateUtil.date());
        this.insert(question);
        String subjectJson = question.getSubjectJson();
        if (StringUtils.isEmpty(subjectJson)) {
            return new ReturnResult();
        }
        return questionSubjectService.saveQuestionSubject(questionId, question.getStatus(), question.getApplyId(), subjectJson);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult updateQuestion(HttpServletRequest request, Question question, SysUser sysUser) {
        int flag = this.updateByPrimaryKeySelective(question);
        if (flag <= 0) {
            return new ReturnResult(ErrorCode.CODE_1,ErrorCode.CODE_ADD_FAIL_MSG);
        }
        String subjectJson = question.getSubjectJson();
        if (StringUtils.isEmpty(subjectJson)) {
            return new ReturnResult(ErrorCode.CODE_1,ErrorCode.CODE_ADD_FAIL_MSG);
        }
        String questionId = question.getId();
        // 需要二维码
        if (StringUtils.equals(question.getType(), BaseConstant.QUESTION_TYPE_QRCODE)) {
            // 生成二维码
            String qrCode = getQrCode(request, question.getId(), question.getApplyId());
            question.setQrCode(qrCode);
            // 如果是非二维码问卷，则直接删除相关数据
            // 删除以前的数据
            QuestionUser questionUserSearch = new QuestionUser();
            questionUserSearch.setQuestionId(questionId);
            questionUserService.delete(questionUserSearch);
        } else {
            // 如果是自定义对象
            if (StringUtils.equals(question.getObjectType(), BaseConstant.QUESTION_OBJECT_TYPE_CUSTOMIZE)) {
                // 保存进QuestionUser
                questionUserService.saveQuestionUser(questionId, question.getUserJson());
            } else if (StringUtils.equals(question.getObjectType(), BaseConstant.QUESTION_OBJECT_TYPE_ALL)) {
                // 所有人（管理员暂算在内）
                questionUserService.saveQuestionAllWxEducationUser(question.getApplyId(), questionId, sysUser);
            } else {
                // 学生或教师
                questionUserService.saveQuestionWxEducationUserByStatus(question.getApplyId(), questionId, question.getObjectType(), sysUser);
            }
        }
        // 是否是发布中,如果是发布，则需要校验时间，时间未到的，处于未开始状态
        if (StringUtils.equals(question.getStatus(), BaseConstant.QUESTION_STATUS_PUBLISH)) {
            Date startTime = question.getStartTime();
            DateTime nowDate = DateUtil.date();
            String nowStr = DateUtil.formatDate(nowDate);
            if (startTime.getTime() > DateUtil.parseDate(nowStr).getTime()) {
                // 未开始
                question.setStatus(BaseConstant.QUESTION_STATUS_NOT_READY);
            }
        }
        this.updateByPrimaryKeySelective(question);
        // 删除现有数据
        QuestionSubject questionSubject = new QuestionSubject();
        questionSubject.setQuestionId(questionId);
        questionSubjectService.delete(questionSubject);
        QuestionSubjectSelect questionSubjectSelect = new QuestionSubjectSelect();
        questionSubjectSelect.setQuestionId(questionId);
        questionSubjectSelectService.delete(questionSubjectSelect);
        return questionSubjectService.saveQuestionSubject(questionId, question.getStatus(), question.getApplyId(), subjectJson);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult copyQuestion(HttpServletRequest request, QuestionVo questionVo) {
        // 复制问卷
        Question oldQuestion = this.selectByPrimaryKey(questionVo.getId());
        Question question = new Question();
        question.setId(BaseUtil.uId());
        question.setApplyId(oldQuestion.getApplyId());
        question.setTitle(questionVo.getTitle());
        // 编辑中
        question.setStatus(BaseConstant.QUESTION_STATUS_EDIT);
        question.setType(oldQuestion.getType());
        question.setObjectType(oldQuestion.getObjectType());
        if (StringUtils.isEmpty(questionVo.getStartTimeStr())) {
            return new ReturnResult(ErrorCode.CODE_1, "请填写开始时间");
        }
        question.setStartTime(DateUtil.parseDate(questionVo.getStartTimeStr()));
        if (StringUtils.isEmpty(questionVo.getEndTimeStr())) {
            return new ReturnResult(ErrorCode.CODE_1, "请填写结束时间");
        }
        question.setEndTime(DateUtil.parseDate(questionVo.getEndTimeStr()));
        // 开始时间和结束时间的判断
        ReturnResult returnResult = checkTime(question.getStartTime(), question.getEndTime());
        if (returnResult.getCode() != 0) {
            return returnResult;
        }
        if (StringUtils.equals(question.getType(), BaseConstant.QUESTION_TYPE_QRCODE)) {
            // 生成二维码
            String qrCode = getQrCode(request, question.getId(), question.getApplyId());
            question.setQrCode(qrCode);
        }
        question.setRemark(questionVo.getRemark());
        question.setCreateTime(DateUtil.date());
        this.insert(question);
        // 复制问卷不加入发布用户
        /*if (StringUtils.equals(questionVo.getType(), BaseConstant.QUESTION_TYPE_OBJECT)) {
            // 保存进QuestionUser
            QuestionUser questionUserSearch = new QuestionUser();
            questionUserSearch.setQuestionId(oldQuestion.getId());
            List<QuestionUser> oldQuestionUserList = questionUserService.select(questionUserSearch);
            List<QuestionUser> questionUserList = new ArrayList<>();
            if (oldQuestionUserList != null && oldQuestionUserList.size() > 0) {
                for (QuestionUser oldQuestionUser : oldQuestionUserList) {
                    QuestionUser questionUser = new QuestionUser();
                    questionUser.setId(BaseUtil.uId());
                    questionUser.setQuestionId(question.getId());
                    questionUser.setApplyId(question.getApplyId());
                    questionUser.setStatus(BaseConstant.QUESTION_USER_STATUS_NO_SUBMIT);
                    questionUser.setUserId(oldQuestionUser.getUserId());
                    questionUser.setCreateTime(DateUtil.date());
                    questionUserList.add(questionUser);
                }
                if (questionUserList != null && questionUserList.size() > 0) {
                    questionUserService.insertList(questionUserList);
                }
            }
        }*/
        // 复制subject和subjectSelect
        QuestionSubjectVo questionSubjectVo = new QuestionSubjectVo();
        questionSubjectVo.setQuestionId(oldQuestion.getId());
        List<QuestionSubject> oldQuestionSubjectList = questionSubjectService.acceptList(questionSubjectVo);
        List<QuestionSubject> questionSubjectList = new ArrayList<>();
        List<QuestionSubjectSelect> questionSubjectSelectList = new ArrayList<>();
        if (oldQuestionSubjectList != null && oldQuestionSubjectList.size() > 0) {
            for (QuestionSubject oldQuestionSubject : oldQuestionSubjectList) {
                QuestionSubject questionSubject = new QuestionSubject();
                questionSubject.setId(BaseUtil.uId());
                questionSubject.setApplyId(oldQuestion.getApplyId());
                questionSubject.setQuestionId(question.getId());
                questionSubject.setTitle(oldQuestionSubject.getTitle());
                questionSubject.setType(oldQuestionSubject.getType());
                questionSubject.setOrderNum(oldQuestionSubject.getOrderNum());
                questionSubject.setCreateTime(DateUtil.date());
                questionSubjectList.add(questionSubject);

                QuestionSubjectSelectVo questionSubjectSelectVo = new QuestionSubjectSelectVo();
                questionSubjectSelectVo.setQuestionId(oldQuestion.getId());
                questionSubjectSelectVo.setSubjectId(oldQuestionSubject.getId());
                List<QuestionSubjectSelect> oldQuestionSubjectSelectList = questionSubjectSelectService.acceptList(questionSubjectSelectVo);
                if (oldQuestionSubjectSelectList != null && oldQuestionSubjectSelectList.size() > 0) {
                    for (QuestionSubjectSelect oldQuestionSubjectSelect : oldQuestionSubjectSelectList) {
                        QuestionSubjectSelect questionSubjectSelect = new QuestionSubjectSelect();
                        questionSubjectSelect.setId(BaseUtil.uId());
                        questionSubjectSelect.setApplyId(oldQuestion.getApplyId());
                        questionSubjectSelect.setQuestionId(question.getId());
                        questionSubjectSelect.setSubjectId(questionSubject.getId());
                        questionSubjectSelect.setTitle(oldQuestionSubjectSelect.getTitle());
                        questionSubjectSelect.setNum(oldQuestionSubjectSelect.getNum());
                        questionSubjectSelect.setScore(oldQuestionSubjectSelect.getScore());
                        questionSubjectSelectList.add(questionSubjectSelect);
                    }
                }
            }
        }
        if (questionSubjectList != null && questionSubjectList.size() > 0) {
            questionSubjectService.insertList(questionSubjectList);
        }
        if (questionSubjectSelectList != null && questionSubjectSelectList.size() > 0) {
            questionSubjectSelectService.insertList(questionSubjectSelectList);
        }
        return new ReturnResult();
    }

    @Override
    public ReturnResult checkTime(Date startTime, Date endTime) {
        // 当前时间问题
        DateTime nowDate = DateUtil.date();
        String nowDateStr = DateUtil.formatDate(nowDate);
        DateTime nowDay = DateUtil.parseDate(nowDateStr);
        if (startTime.getTime() < nowDay.getTime()) {
            return new ReturnResult(ErrorCode.CODE_1, "开始时间不能小于当前时间");
        }
        if (endTime.getTime() < nowDay.getTime()) {
            return new ReturnResult(ErrorCode.CODE_1, "结束时间不能小于当前时间");
        }
        // 开始时间和结束时间的正确性
        if (startTime.getTime() > endTime.getTime()) {
            return new ReturnResult(ErrorCode.CODE_1, "开始时间不能大于结束时间");
        }
        return new ReturnResult();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult updateStatus(String id, String status, SysUser sysUser) {
        Question question = this.selectByPrimaryKey(id);
        question.setId(id);
        // 如果是发布，则需要判断时间
        if (StringUtils.equals(status, BaseConstant.QUESTION_STATUS_PUBLISH)) {
            Date startTime = question.getStartTime();
            DateTime nowDate = DateUtil.date();
            String nowStr = DateUtil.formatDate(nowDate);
            if (startTime.getTime() > DateUtil.parseDate(nowStr).getTime()) {
                // 未开始
                question.setStatus(BaseConstant.QUESTION_STATUS_NOT_READY);
            } else {
                question.setStatus(status);
            }
        } else {
            question.setStatus(status);
        }
        // 如果是自定义对象
        if (StringUtils.equals(question.getObjectType(), BaseConstant.QUESTION_OBJECT_TYPE_CUSTOMIZE)) {
            // 保存进QuestionUser
            questionUserService.saveQuestionUser(id, question.getUserJson());
        } else if (StringUtils.equals(question.getObjectType(), BaseConstant.QUESTION_OBJECT_TYPE_ALL)) {
            // 所有人（管理员暂算在内）
            questionUserService.saveQuestionAllWxEducationUser(question.getApplyId(), id, sysUser);
        } else {
            // 学生或教师
            questionUserService.saveQuestionWxEducationUserByStatus(question.getApplyId(), id, question.getObjectType(), sysUser);
        }
        int flag = this.updateByPrimaryKeySelective(question);
        if (flag <= 0) {
            return new ReturnResult(ErrorCode.CODE_1,ErrorCode.CODE_ADD_FAIL_MSG);
        }
        return new ReturnResult();
    }

    @Override
    public void exportUserScoreExcel(HttpServletResponse response, String questionId) {
        // 动态列
        List<ExcelExportEntity> entity = new ArrayList<>();
        List<Map<String, Object>> list = new ArrayList<>();
        // 构造对象等同于@Excel
        QuestionSubjectVo questionSubjectVo = new QuestionSubjectVo();
        questionSubjectVo.setQuestionId(questionId);
        List<QuestionSubject> subjectList = questionSubjectService.acceptList(questionSubjectVo);
        if (CollUtil.isEmpty(subjectList)) {
            EasyPoiUtil.exportDyncExcel(list, entity, "用户答题信息", "用户答题信息","用户答题信息.xls", response);
            return;
        }
        // map题目
        Map<String, List<QuestionSubjectSelect>> subjectSelectMap = new HashMap<>();
        for (QuestionSubject subject : subjectList) {
            QuestionSubjectSelectVo questionSubjectSelectVo = new QuestionSubjectSelectVo();
            questionSubjectSelectVo.setQuestionId(questionId);
            questionSubjectSelectVo.setSubjectId(subject.getId());
            List<QuestionSubjectSelect> subjectSelectList = questionSubjectSelectService.acceptList(questionSubjectSelectVo);
            subjectSelectMap.put(subject.getId(), subjectSelectList);
            entity.add(new ExcelExportEntity(String.format("第%s题", subject.getOrderNum()), subject.getId()));
        }
        // 查询到所有学生
        List<QuestionUserDto> questionUserList = questionScoreService.selectUserList(questionId);
        if (CollUtil.isEmpty(questionUserList)) {
            EasyPoiUtil.exportDyncExcel(list, entity, "用户答题信息", "用户答题信息","用户答题信息.xls", response);
            return;
        }
        // 得出学生答案
        QuestionScore questionScoreSearch = new QuestionScore();
        questionScoreSearch.setQuestionId(questionId);
        List<QuestionScore> scoreList = questionScoreService.select(questionScoreSearch);
        if (CollUtil.isEmpty(scoreList)) {
            EasyPoiUtil.exportDyncExcel(list, entity, "用户答题信息", "用户答题信息","用户答题信息.xls", response);
            return;
        }
        // 所有学生
        for (QuestionUserDto questionUser : questionUserList) {
            Map<String, Object> map = new HashMap<>();
            // 答案
            for (QuestionSubject subject : subjectList) {
                // 题目
                List<QuestionSubjectSelect> subjectSelectList = subjectSelectMap.get(subject.getId());
                for (QuestionScore questionScore : scoreList) {
                    if (StringUtils.equals(questionUser.getUserId(), questionScore.getUserId()) && StringUtils.equals(subject.getId(), questionScore.getSubjectId())) {
                        // 查询到题目，然后在查询答案
                        // 排除填空题
                        String score = "";
                        if (StringUtils.equals(subject.getType(), BaseConstant.QUESTION_SUBJECT_THREE)) {
                            score = questionScore.getScoreList();
                        // 查询其他的
                        } else {
                            if (CollUtil.isEmpty(subjectSelectList)) {
                                continue;
                            }
                            // 区分有没有逗号，如果有，多选题
                            String userScoreList = questionScore.getScoreList();
                            if (StringUtils.isEmpty(userScoreList)) {
                                continue;
                            }
                            for (QuestionSubjectSelect subjectSelect : subjectSelectList) {
                                if (StringUtils.contains(userScoreList, subjectSelect.getId())) {
                                    if (StringUtils.isEmpty(score)) {
                                        score = subjectSelect.getNum();
                                    } else {
                                        score += "," + subjectSelect.getNum();
                                    }
                                }
                            }
                        }
                        map.put(subject.getId(), score);
                        continue;
                    }
                }
            }
            list.add(map);
        }
        // 导出操作
        EasyPoiUtil.exportDyncExcel(list, entity, "用户答题信息", "用户答题信息","问卷明细.xls", response);
    }

    @Override
    public void exportTotalExcel(HttpServletResponse response, String questionId) {
        // 动态列
        List<ExcelExportEntity> entity = new ArrayList<>();
        List<Map<String, Object>> list = new ArrayList<>();
        entity.add(new ExcelExportEntity("题目", "A", 100));
        entity.add(new ExcelExportEntity("统计", "B"));
        // 题目
        QuestionSubjectVo questionSubjectVo = new QuestionSubjectVo();
        questionSubjectVo.setQuestionId(questionId);
        List<QuestionSubject> subjectList = questionSubjectService.acceptList(questionSubjectVo);
        QuestionScore questionScore = new QuestionScore();
        questionScore.setQuestionId(questionId);
        long allCount = questionScoreService.selectCountGroupByUser(questionScore);
        if (CollUtil.isNotEmpty(subjectList)) {
            for (QuestionSubject subject : subjectList) {
                // 标题
                Map<String, Object> subjectMap = new HashMap<>();
                subjectMap.put("A", subject.getOrderNum() + "、" + subject.getTitle());
                list.add(subjectMap);
                // 查询是否是选择
                if (StringUtils.equals(subject.getType(), BaseConstant.QUESTION_SUBJECT_THREE)) {
                    continue;
                }
                QuestionSubjectSelectVo questionSubjectSelectSearch = new QuestionSubjectSelectVo();
                questionSubjectSelectSearch.setQuestionId(questionId);
                questionSubjectSelectSearch.setSubjectId(subject.getId());
                // 获取每个答案的回答总数和题目回答
                List<QuestionSubjectSelect> subjectSelectList = questionSubjectSelectService.selectEntityList(questionSubjectSelectSearch);
                if (CollUtil.isNotEmpty(subjectSelectList)) {
                    for (QuestionSubjectSelect subjectSelect : subjectSelectList) {
                        Map<String, Object> selectMap = new HashMap<>();
                        // 答案
                        selectMap.put("A", subjectSelect.getNum() + "." + subjectSelect.getTitle());
                        selectMap.put("B", subjectSelect.getSelectCount() + "/" + allCount);
                        list.add(selectMap);
                    }
                }
            }
        }
        // 创建sheet
        ExportParams exportParamsA = new ExportParams("用户答题信息", "用户答题信息");
        exportParamsA.setStyle(ExcelExportStylerUtil.class);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParamsA, entity, list);
        if (workbook != null) {
            ExcelExportService service = new ExcelExportService();
            // 多加sheet
            for (QuestionSubject subject : subjectList) {
                if (StringUtils.equals(subject.getType(), BaseConstant.QUESTION_SUBJECT_THREE)) {
                    List<ExcelExportEntity> entityB = new ArrayList<>();
                    List<Map<String, Object>> listB = new ArrayList<>();
                    ExcelExportEntity excelExportEntity = new ExcelExportEntity("答案", "A", 100);
                    excelExportEntity.setWrap(true);
                    entityB.add(excelExportEntity);
                    // 每道题目
                    QuestionScoreVo questionScoreVo = new QuestionScoreVo();
                    questionScoreVo.setQuestionId(questionId);
                    questionScoreVo.setSubjectId(subject.getId());
                    List<QuestionScore> questionScoreList = questionScoreService.accept(questionScoreVo);
                    if (CollUtil.isEmpty(questionScoreList)) {
                        continue;
                    }
                    for (QuestionScore entityScore : questionScoreList) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("A", entityScore.getScoreList());
                        listB.add(map);
                    }
                    ExportParams exportParams = new ExportParams(subject.getTitle(), "简答题" + subject.getOrderNum());
                    exportParams.setStyle(ExcelExportStylerUtil.class);
                    service.createSheetForMap(workbook, exportParams, entityB, listB);
                }
            }
            EasyPoiUtil.downLoadExcel("问卷统计结果.xls", response, workbook);
        }
        // 导出操作
        // EasyPoiUtil.exportDyncExcel(list, entity, "用户答题信息", "用户答题信息","用户答题信息.xls", response);
    }

    @Override
    public Question getInfo(String id, String userId) {
        Question question = this.selectByPrimaryKey(id);
        // 需要获取题目
        if (question == null) {
            return null;
        }
        // 排序
        QuestionSubjectVo questionSubjectVo = new QuestionSubjectVo();
        questionSubjectVo.setQuestionId(id);
        List<QuestionSubject> subjectList = questionSubjectService.acceptList(questionSubjectVo);
        // 得出学生答案
        List<QuestionScore> scoreList = new ArrayList<>();
        if (StringUtils.isNotEmpty(userId)) {
            QuestionScore questionScoreSearch = new QuestionScore();
            questionScoreSearch.setQuestionId(id);
            questionScoreSearch.setUserId(userId);
            scoreList = questionScoreService.select(questionScoreSearch);
        }
        // 如果是自定义问卷，带出人员
        if (StringUtils.equals(question.getObjectType(), BaseConstant.QUESTION_OBJECT_TYPE_CUSTOMIZE) && StringUtils.equals(question.getStatus(), BaseConstant.QUESTION_STATUS_EDIT)) {
            List<QuestionUserDto> questionUserList = questionUserService.selectByQuestionId(question.getId(), null);
            question.setQuestionUserList(questionUserList);
        }
        // 根据需求，不考虑显示页面查看人员
        /*else {
            // 发布中的，分开显示
            List<QuestionUserDto> questionUserList = questionUserService.selectByQuestionId(question.getId(), BaseConstant.QUESTION_USER_STATUS_YES_SUBMIT);
            question.setQuestionUserList(questionUserList);
            List<QuestionUserDto> noSubmitQuestionUserList = questionUserService.selectByQuestionId(question.getId(), BaseConstant.QUESTION_USER_STATUS_NO_SUBMIT);
            question.setNoSubmitQuestionUserList(noSubmitQuestionUserList);
        }*/
        if (subjectList != null && subjectList.size() > 0) {
            for (QuestionSubject subject : subjectList) {
                QuestionSubjectSelectVo questionSubjectSelectSearch = new QuestionSubjectSelectVo();
                questionSubjectSelectSearch.setQuestionId(question.getId());
                questionSubjectSelectSearch.setSubjectId(subject.getId());
                // 需要得出答案,排序
                List<QuestionSubjectSelect> subjectSelectList = questionSubjectSelectService.acceptList(questionSubjectSelectSearch);
                if (StringUtils.isNotEmpty(userId) && scoreList != null && scoreList.size() > 0) {
                    for (QuestionScore questionScore : scoreList) {
                        if (StringUtils.equals(subject.getId(), questionScore.getSubjectId())) {
                            subject.setAnswer(questionScore.getScoreList());
                            break;
                        }
                    }
                }
                subject.setSelectList(subjectSelectList);
            }
            question.setSubjectList(subjectList);
        }
        return question;
    }

    @Override
    public int deleteQuestion(String id) {
        //筛选条件
        Example example = new Example(Notice.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(id)) {
            criteria.andIn("id", Arrays.asList(id.split(",")));
        }
        return questionDao.deleteByExample(example);
    }

    /**
     * 问卷按月统计
     *
     * @param questionVo 参数传入对象
     * @return ReturnResult
     * @author rong yuan
     * @date 2019-08-21 14:18
     */
    @Override
    public ReturnResult statisticsByMonth(QuestionVo questionVo) {
        List<String> monthList = new ArrayList<>();
        List<Integer> questionNumList = new ArrayList<>();
        String year = String.valueOf(DateUtil.thisYear());
        for (int i = 1; i <= 12; i++) {
            monthList.add(i + "月份");
            if (i < 10) {
                questionVo.setCreateTime(year + "-0" + i);
            } else {
                questionVo.setCreateTime(year + "-" + i);
            }
            List<Question> assetWarrantyList = this.listByExample(questionVo);
            questionNumList.add(assetWarrantyList == null ? 0 : assetWarrantyList.size());
        }
        List<Object> result = new ArrayList<>();
        result.add(monthList);
        result.add(questionNumList);
        return new ReturnResult(result);
    }

    /**
     * list 查询
     *
     * @param questionVo 参数传入对象
     * @return List<Question>
     * @author rong yuan
     * @date 2019-08-21 14:22
     */
    @Override
    public List<Question> listByExample(QuestionVo questionVo) {
        Example example = new Example(Question.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(questionVo.getApplyId())) {
            criteria.andEqualTo("applyId", questionVo.getApplyId());
        }
        if (StringUtils.isNotBlank(questionVo.getCreateTime())) {
            criteria.andCondition("date_format(create_time, '%Y-%m') = '" + questionVo.getCreateTime() + "'");
        }
        return questionDao.selectByExample(example);
    }

    @Override
    public Question getTotalInfo(String id) {
        Question question = this.selectByPrimaryKey(id);
        // 需要获取题目
        if (question == null) {
            return null;
        }
        QuestionSubjectVo questionSubjectVo = new QuestionSubjectVo();
        questionSubjectVo.setQuestionId(id);
        List<QuestionSubject> subjectList = questionSubjectService.acceptList(questionSubjectVo);
        QuestionScore questionScore = new QuestionScore();
        questionScore.setQuestionId(id);
        long allCount = questionScoreService.selectCountGroupByUser(questionScore);
        question.setAllCount(String.valueOf(allCount));
        if (subjectList != null && subjectList.size() > 0) {
            for (QuestionSubject subject : subjectList) {
                QuestionSubjectSelectVo questionSubjectSelectSearch = new QuestionSubjectSelectVo();
                questionSubjectSelectSearch.setQuestionId(question.getId());
                questionSubjectSelectSearch.setSubjectId(subject.getId());
                // 获取每个答案的回答总数和题目回答
                List<QuestionSubjectSelect> subjectSelectList = questionSubjectSelectService.selectEntityList(questionSubjectSelectSearch);
                subject.setSelectList(subjectSelectList);
            }
            question.setSubjectList(subjectList);
        }
        return question;
    }

    @Override
    public void updateStatusByTime() {
        // 关闭当天结束,发布中的
        questionDao.closeQuestion();
        // 开启明天开始，未开始的
        questionDao.openQuestion();
    }

    @Override
    public ReturnResult pageStatisticsUser(QuestionVo questionVo, int pageSize, int pageNum) {
        // 统计已答卷人员
        // 1、指定人员objectType=4，可以统计出未答卷人员
        // 2、扫码统计不出，全部、教师、学生可以直接查询，不建议，直接统计已答卷人员
        PageHelper.startPage(pageNum, pageSize);
        List<QuestionUserDto> list;
        if (StringUtils.equals(questionVo.getType(), BaseConstant.QUESTION_TYPE_OBJECT)) {
            list = questionUserService.selectByQuestionId(questionVo.getId(), null);
        } else {
            list = questionUserService.selectQrcodeByQuestionId(questionVo.getId());
        }
        PageInfo<QuestionUserDto> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    @Override
    public ReturnResult importExcel(MultipartFile file, String applyId, SysUser sysUser) {
        // 用户表中是否存在数据
        ExcelImportResult<QuestionUserVerifyImportVo> result = EasyPoiUtil.importExcelResult(file, 1, 1, QuestionUserVerifyImportVo.class);
        List<QuestionUserVerifyImportVo> questionUserList = result.getList();
        List<WxEducationUser> wxEducationUserShow = new ArrayList<>();
        if (questionUserList != null && questionUserList.size() > 0) {
            Map<String, QuestionUserImportVo> questionUserMap = new HashMap<>();
            String key;
            for (QuestionUserImportVo questionUser : questionUserList) {
                key = questionUser.getUserNumber();
                if (questionUserMap.keySet().contains(key)) {
                    continue;
                }
                questionUserMap.put(key, questionUser);
            }
            List<WxEducationUser> wxEducationUserList = new ArrayList<>();
            for (Map.Entry<String, QuestionUserImportVo> entry : questionUserMap.entrySet()) {
                QuestionUserImportVo userFrom = entry.getValue();
                // 查询账号是否存在
                WxEducationUserVo wxEducationUserVo = new WxEducationUserVo();
                wxEducationUserVo.setUserNumber(userFrom.getUserNumber());
                wxEducationUserVo.setCreateUser(sysUser.getId());
                List<WxEducationUser> list = wxEducationUserService.listExample(wxEducationUserVo);
                if (list != null && list.size() > 0) {
                    wxEducationUserShow.addAll(list);
                    continue;
                }
                // 账号不存在，保存进用户表
                WxEducationUser wxEducationUser = new WxEducationUser();
                String mobile = userFrom.getMobile();
                wxEducationUser.setId(BaseUtil.uId());
                wxEducationUser.setApplyId(applyId);
                wxEducationUser.setLoginName(userFrom.getUserNumber());
                wxEducationUser.setMobile(userFrom.getMobile());
                wxEducationUser.setName(userFrom.getName());
                wxEducationUser.setUserNumber(userFrom.getUserNumber());
                if (StringUtils.isNotEmpty(mobile) && mobile.length() == 11) {
                    wxEducationUser.setPassword(MD5Util.MD5Encode(StrUtil.sub(mobile, 5, 11)));
                } else {
                    wxEducationUser.setPassword(MD5Util.MD5Encode(BaseConstant.DEFAULT_EDUCATION_USER_PASSWORD));
                }
                wxEducationUser.setUserType(userFrom.getUserType());
                wxEducationUser.setRemoveTag(BaseConstant.REMOVE_TAG_NO);
                wxEducationUser.setStatus(BaseConstant.BASE_STATUS_YES);
                wxEducationUser.setCreateUser(sysUser.getId());
                wxEducationUser.setUpdateUser(sysUser.getId());
                wxEducationUser.setCreateTime(DateUtil.date());
                wxEducationUser.setUpdateTime(DateUtil.date());
                wxEducationUserList.add(wxEducationUser);
                wxEducationUserShow.add(wxEducationUser);
            }
            // 保存
            if (wxEducationUserList != null && wxEducationUserList.size() > 0) {
                wxEducationUserService.insertList(wxEducationUserList);
            }
        }
        if (result.isVerfiyFail()) {
            // 如果错误，打印出提醒，直接返回
            int successNum = 0;
            int failNum = result.getFailList().size();
            if (result.getList() != null && result.getList().size() > 0) {
                successNum = result.getList().size();
            }
            String errorMsg = String.format("共导入%s条，成功%s条，失败%s条。", successNum + failNum, successNum, failNum);
            List<QuestionUserVerifyImportVo> failList = result.getFailList();
            // 需要将成功条数也返回
            Map<String, Object> resutlMap = new HashMap<>();
            resutlMap.put("failList", failList);
            resutlMap.put("successList", wxEducationUserShow);
            return new ReturnResult(ErrorCode.CODE_1, resutlMap, errorMsg);
        }
        return new ReturnResult(wxEducationUserShow);
    }

    private String getQrCode(HttpServletRequest request, String id, String applyId) {
        String qrCode = "";
        String realPath = FilePathUtil.acceptCheckRealPath(request);
        String path = realPath + "/upload/question/" + id + ".png";
        File dicFile = new File(realPath + "/upload/question/");
        if  (!dicFile .exists()  && !dicFile .isDirectory()) {
            dicFile .mkdir();
        }
        try {
            File file = new File(path);
            if (file.exists()) {
                // 删除问卷，重新生成
                file.delete();
            }
            OutputStream out = new FileOutputStream(path);
            String url = ProProperties.getInstance().getBaseUrl() + ProProperties.getInstance().getWxOauthURL() + "?applyId=" + applyId +
                    "&path=/phone/question/questionEdit&pathParams=questionId*" + id;
            new SimpleQrcodeGenerator().generate(url).toStream(out);
            qrCode = "/upload/question/" + id + ".png";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return qrCode;
    }
}
